$(document).ready(function () {
		
		$('.actions a.btn-primary, .page-header a.btn-primary').click(function(event) {
			event.preventDefault();
			
			var url = $(this).attr('href');
			var title = $(this).attr('title');
			var container = $('#form-modal');
			var header = container.children('.modal-header');
			var content = container.children('.modal-body');
			var footer = container.children('.modal-footer');
			
			$("#ajax-indicator").show();
			content.empty();
            $.get(url, function (data) {
            	header.children('h4:first').text(title);
				if (url.indexOf('add') >= 0) {
					footer.children('button:last-child').show();
				} else if (url.indexOf('edit') >= 0) {
					footer.children('button:last-child').show();
				} else if (url.indexOf('view') >= 0) {
					footer.children('button:first-child').children('span').text('Fechar');
					footer.children('button:last-child').hide();
				}
				content.html(data);
                container.modal();  
            })
            .always(function(){
            	$("#ajax-indicator").hide();
            });
            
		});
		
		$('#form-modal button.btn-primary').click(function(event) {
			event.preventDefault();
			var button = $(this);
			var clone = button.clone(true);
			var content =  $("#form-modal .modal-body");
			var form = content.children('form');
			
			$("#ajax-indicator").show();
			button.addClass('disabled').children('span').text('Salvando...').attr({disabled: 'disabled'});
		    $.post(form.attr('action'), form.serialize(), function (response) {
		        if ($(response).find('.error').length) {
		        	content.html(response);
		        	button.replaceWith(clone);
		        } else {
		           location.reload();
		        }
		    })
		    .always(function(){
		    	$("#ajax-indicator").hide();
		    });
		});
		
	});